package com.ktjiaoyu.crm.service.impl;


import com.ktjiaoyu.crm.mapper.RightMapper;
import com.ktjiaoyu.crm.mapper.RoleMapper;
import com.ktjiaoyu.crm.pojo.Right;
import com.ktjiaoyu.crm.pojo.Role;
import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.RoleService;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service("roleService")
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RightMapper rightMapper;
    @Override
    public List<Role> findAllRoles() {
        return roleMapper.findAll();
    }

    @Override
    public List<Right> findAllRights() {
        return rightMapper.findAll();
    }

    @Override
    public List<Right> findRightsByRole(Role role) {
        return rightMapper.findRightsByRolesOrderByRightCode(role);
    }

    @Override
    public Role saveRole(Role role) {
        return roleMapper.save(role);
    }

    @Override
    public void deleteRoleById(Long roleId) {
        roleMapper.deleteById(roleId );
    }

    @Override
    public void deleteRole(Role role) {
        roleMapper.delete(role);
    }

    @Override
    public Role getRole(Long roleId) {
        return roleMapper.findById(roleId).get();
    }

    @Override
    public Page<Role> findRole(String roleName, Pageable pageable) {
        return (Page<Role>) roleMapper.findRolesByRoleNameLike("%"+roleName+"%",pageable);
    }

    @Override
    public List<Right> findRightsByRole() {
        return rightMapper.findAll();
    }

    @Override
    public Role findRoleByUsers(User user) {
            return roleMapper.findRoleByUsers(user);
    }

    @Override
    public Map<String,String> loadFilterChainDefinitions() {
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();//必须使用LinkedHashMap(有序集合)
        //配置可以匿名访问的资源（URL）；静态资源
        filterChainDefinitionMap.put("/css/**", "anon");
        filterChainDefinitionMap.put("/fonts/**", "anon");
        filterChainDefinitionMap.put("/images/**", "anon");
        filterChainDefinitionMap.put("/js/**", "anon");
        filterChainDefinitionMap.put("/localcss/**", "anon");
        filterChainDefinitionMap.put("/localjs/**", "anon");
        filterChainDefinitionMap.put("/login", "anon");
        filterChainDefinitionMap.put("/logout", "logout");//注销过滤器，自动注销
//动态授权
        List<Right> rights = findAllRights();
        for (Right right : rights) {
            if (right.getRightUrl() != null && !right.getRightUrl().trim().equals("")) {
                filterChainDefinitionMap.put(right.getRightUrl(), "perms[" + right.getRightText() + "]");
            }
        }
        //配置认证访问：其他资源（URL）必须认证通过才能访问
        filterChainDefinitionMap.put("/**", "authc");//必须放在过滤器链的最后面
        return filterChainDefinitionMap;
    }

    @Override
    public void reloadFilterChainDefinitions() {//重新加载动态权限，配置权限验证规则
        try{
            HttpServletRequest request=
                    ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            ServletContext servletContext=request.getSession().getServletContext();
            AbstractShiroFilter shiroFilter=
                    (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean(
                            "shiroFilterFactory");
            synchronized (shiroFilter){
                //获取过滤管理器
                PathMatchingFilterChainResolver filterChainResolver= (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
                DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
                //清空初始权限配置
                manager.getFilterChains().clear();
                //重新加载动态权限，配置权限验证规则
                Map<String, String> chains = loadFilterChainDefinitions();
                // System.out.println("chains-------"+chains);
                for (Map.Entry<String, String> entry : chains.entrySet()) {
                    String url = entry.getKey();String chainDefinition = entry.getValue().trim().replace(" ", " ");
                    manager.createChain(url, chainDefinition);
                }
                System.out.println("更新权限成功！！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
